package com.mind.ridge.filter;


import com.alibaba.fastjson.JSON;
import com.mind.ridge.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author mind
 */
@Slf4j
@WebFilter(filterName = "checkUriFilter", urlPatterns = "/*")
public class CheckUriFilter implements Filter {

    /**
     * 路径匹配器 支持通配符
     */
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次请求的uri
        String requestURI = request.getRequestURI();

        log.info("拦截到的请求：{}",requestURI);

        //设置可通过的uri
        String[] uris = {
                "/employee/login",
                "employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"

        };

        //判断是否可通过
        if (canPass(uris, requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        //判断用户是否已登录，若已登录则直接放行
        Long id = (Long) request.getSession().getAttribute("id");
        if (id != null) {
            log.info("当前用户" + id.toString());
            filterChain.doFilter(request, response);
            return;
        }

        //判断用户是否已登录，若已登录则直接放行
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (userId != null) {
            log.info("当前用户" + userId.toString());
            filterChain.doFilter(request, response);
            return;
        }

        //否则给前端响应JSON格式的数据--错误信息并跳转到登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }


    public boolean canPass(String[] uris, String requestURI) {
        for (String uri : uris) {
            boolean res = PATH_MATCHER.match(uri, requestURI);
            if (res) {
                return true;
            }
        }
        return false;
    }

}
